package org.xy.sys.service;

import org.springframework.stereotype.Component;
import org.xy.common.daoitf.BaseMapper;
import org.xy.common.serviceitf.BaseService;
import org.xy.sys.dao.TypeMapper;
import org.xy.sys.domain.TypeInfo;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class TypeService extends BaseService<TypeInfo> {

    @Resource(name = "typeMapper")
    private TypeMapper typeMapper;

    public BaseMapper<TypeInfo> getDao() {
        return typeMapper;
    }

    public List<Map<String, Object>> queryAllTree(TypeInfo cond) {
        cond.setOrderBy("t.seq_num asc,t.id desc");
        List<TypeInfo> infoData = getDao().queryAll(cond);
        TypeInfo root = new TypeInfo();
        root.setId(0L);
        root.setName("分类");
        return buildTree(infoData,root);
    }

    public List<Map<String, Object>> queryTree(TypeInfo cond) {
        cond.setOrderBy("t.seq_num asc,t.id desc");
        List<TypeInfo> infoData = getDao().queryAll(cond);
        return buildTree(infoData,null);
    }

    /**
     * 构建树形结构（layui的树是真心不好，结构还得自己拼装）
     * @param infoList
     * @param parent
     * @return
     */
    private List<Map<String, Object>> buildTree(List<TypeInfo> infoList, TypeInfo parent) {
        List<Map<String, Object>> resList = new ArrayList<Map<String, Object>>();
        if (parent != null) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", parent.getId());
            map.put("title", parent.getName());
            map.put("spread", true);      //设置是否展开
            List<TypeInfo> subList = getChildren(infoList, parent.getId());
            if (subList.size() > 0) {
                List<Map<String, Object>> subInfoList = new ArrayList<Map<String, Object>>();
                for (TypeInfo subInfo : subList) {
                    subInfoList.addAll(buildTree(infoList, subInfo));

                }
                map.put("children", subInfoList);
            }
            resList.add(map);
        } else {
            List<TypeInfo> subList = getChildren(infoList, 0L);
            if (subList.size() > 0) {
                for (TypeInfo subInfo : subList) {
                    resList.addAll(buildTree(infoList, subInfo));
                }
            }
        }

        return resList;
    }

    /**
     * 子节点
     * @param infoList
     * @param id
     * @return
     */
    private List<TypeInfo> getChildren(List<TypeInfo> infoList, Long id) {
        List<TypeInfo> subList = new ArrayList<TypeInfo>();
        for (TypeInfo info : infoList) {
            if (id.equals(info.getParentId())) {
                subList.add(info);
            }
        }
        return subList;
    }
}
